/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useState } from 'react';
import './index.scss';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';

type FormData = {
  vector?: pickedLineData | pickedFaceData;
  curve?: pickedLineData;
  direction: 1 | -1;
};

type Params = {
  mode: 'extremal';
  vector: string;
  curve: string;
  direction: 1 | -1;
};

function CommandVertexExtremal({
  title,
  onClose,
  props,
}: CurvedCmdDialogParams) {
  const initData: FormData = { direction: 1 };
  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }
    const params: Params = props.params;
    const { vector, curve, direction } = params;

    await initEditDependency([vector, curve]);

    setFormData({
      vector: picker.generatePickObjByPickID(vector) as
        | pickedLineData
        | pickedFaceData,
      curve: picker.generatePickObjByPickID(curve) as pickedLineData,
      direction,
    });
  }, [props?.shape]);

  const isFormDataValid = () => {
    const { vector, curve } = formData;

    return curve != null && vector != null;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const {
    initEditDependency,
    initingEdit,
    clear,
    confirmCommand,
    isLoading,
    isPreviewLoading,
  } = useCommand('cmd-vertex-extremal', {
    commandName: 'CreateVertex',
    editDxid: props?.shape,
    onClose,
    finishDraw: checkAndFinishDraw,
  });

  const execute = (preview: boolean) => {
    const { curve, vector, direction } = formData;

    return confirmCommand(
      {
        a: {
          mode: 'extremal',
          curve: curve.edgeId,
          vector: getIdOfPickedObj(vector),
          direction,
        },
      },
      preview,
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      vector: {
        type: 'string',
        format: PickInputRJSFFormat.PickDirection,
      },
      curve: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      direction: {
        type: 'number',
        title: '方向',
        oneOf: [
          { title: '最大值', const: 1 },
          { title: '最小值', const: -1 },
        ],
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      submitLoading={isLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        vector: {
          'ui:placeholder': '请输入方向',
          'ui:autofocus': true,
        },
        curve: {
          'ui:placeholder': '请输入曲线',
        },
        direction: {
          'ui:widget': 'radio',
          'ui:classNames': 'command-form_cmd-point-extremal_direction',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdVertexExtremal: CurvedBaseCommand = {
  id: 'CmdVertexExtremal',
  label: 'command.vertex-extremal',
  icon: 'commands/curved/end-point',
  create: (label, onClose, props) => (
    <CommandVertexExtremal
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
